package com.example.demo.realm;

import com.example.demo.entity.Login;
import com.example.demo.service.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class LoginRealm extends AuthorizingRealm {

    @Autowired
    private LoginService loginService;

//    自定义shiro过滤器

    //    授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        获取当前登录的用户信息
        Subject subject = SecurityUtils.getSubject();
        Login login = (Login) subject.getPrincipal();

//        设置角色
        Set<String> roles = new HashSet<>();
        roles.add(login.getRole());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);

//        设置权限
        info.addStringPermission(login.getPerms());

        return info;
    }

    //    认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        Login login = loginService.findByUsername(token.getUsername());
        if (login != null) {
            return new SimpleAuthenticationInfo(login, login.getPassword(), getName());
        }
        return null;
    }
}
